package com.cd.javacxy.exception;

import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yanghy
 * @version V1.0
 * @date 2019/11/9
 */
@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResponse handle(ValidationException exception) {
        if (log.isDebugEnabled()) {
            log.debug("参数校验异常", exception);
        }
        StringBuilder msg = new StringBuilder();
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                msg.append(item.getMessage());
            }
        }
        return AjaxResponse.builder()
                .errorMsg(msg.toString())
                .code(ResponseCode.BAD_REQUEST.getCode())
                .build();
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResponse handleBindException(BindException exception) {
        List<String> defaultMsg = exception.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        if (log.isDebugEnabled()) {
            log.debug("参数校验异常={}", defaultMsg.get(0));
        }
        return AjaxResponse.builder()
                .errorMsg(defaultMsg.get(0))
                .code(ResponseCode.BAD_REQUEST.getCode())
                .build();
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BaseException.class)
    public AjaxResponse handleBaseException(BaseException e) {
        return AjaxResponse.builder()
                .errorMsg(e.getMsg())
                .code(e.getCode())
                .build();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResponse handleException(Exception e) {
        log.info("全局异常拦截Exception", e);
        return AjaxResponse.builder()
                .errorMsg("服务器开小差啦")
                .code(500)
                .build();
    }
}
